package com.tn.service.basic.impl;
import com.tn.controller.alarm.common.enums.CommonCodeEnum;
import com.tn.controller.alarm.common.model.PageInput;
import com.tn.controller.alarm.common.model.PageResult;
import com.tn.controller.alarm.common.model.basic.vo.KeyBasicDataVO;
import com.tn.controller.alarm.common.model.basic.vo.KeyBasicQueryVO;
import com.tn.dao.basic.IBasicDataDao;
import com.tn.exception.DatabaseOperationFailedException;
import com.tn.service.basic.IBasicDataService;
import com.tn.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @description: 货品，物流公司，service实现类
 * @packageName: com.tn.service.basic.impl$
 * @author: Zhangfeng
 * @createTime: 2023-04-06
 * @version: V1.0.0
 */
@Slf4j
@Service
public class BasicDataServiceImpl implements IBasicDataService {
    /**
     * 数据访问层
     */
    private IBasicDataDao basicDataDao;

    @Autowired
    public void setIBasicDataDao(IBasicDataDao basicDataDao) {
        this.basicDataDao = basicDataDao;
    }

    @Override
    public int addBasicData(KeyBasicDataVO basicDataVO) throws DatabaseOperationFailedException {
        KeyBasicDataVO check = checkExistsBasicDataByKey(basicDataVO.getKeyCode());
        if (check!=null) {
            throw new DatabaseOperationFailedException(CommonCodeEnum.EXISTS.getCode(),
                    CommonCodeEnum.EXISTS.getMessage());
        }
        basicDataVO.setCreateTime(DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
        return basicDataDao.addBasicData(basicDataVO);
    }

    @Override
    public void deleteBasicData(KeyBasicDataVO basicDataVO) throws DatabaseOperationFailedException {
        basicDataDao.deleteBasicData(basicDataVO);
    }

    @Override
    public int modifyBasicData(KeyBasicDataVO basicDataVO) throws DatabaseOperationFailedException {
        if(!StringUtils.isEmpty(basicDataVO.getKeyCode())){
            KeyBasicDataVO check = checkExistsBasicDataByKey(basicDataVO.getKeyCode());
            if (check!=null && !check.getId().equals(basicDataVO.getId())) {
                throw new DatabaseOperationFailedException(CommonCodeEnum.EXISTS.getCode(),
                        CommonCodeEnum.EXISTS.getMessage());
            }
        }
        KeyBasicDataVO cameraData = basicDataDao.queryBasicDataById(basicDataVO.getId());
        if (null == cameraData) {
            throw new DatabaseOperationFailedException(CommonCodeEnum.NOT_EXISTS.getCode(),
                    CommonCodeEnum.NOT_EXISTS.getMessage());
        }
        return basicDataDao.updateBasicData(basicDataVO);
    }

    @Override
    public List<KeyBasicDataVO> queryList(KeyBasicDataVO basicDataVO) {
        return basicDataDao.queryList(basicDataVO);
    }

    @Override
    public KeyBasicDataVO queryBasicDataByKey(String keyCode) {
        return basicDataDao.queryBasicDataByKey(keyCode);
    }
    /**
     * 校验摄像头名称是否已存在
     *
     * @param goodsName 名称
     * @return 是否存在
     */
    private KeyBasicDataVO checkExistsBasicDataByName(String goodsName) {
        return  basicDataDao.checkExistsBasicDataByName(goodsName);
    }

    private KeyBasicDataVO checkExistsBasicDataByKey(String keys) {
        return  basicDataDao.checkExistsBasicDataByKey(keys);
    }

    /*public String importExcel(MultipartFile multipartFile,String kind) {
        String fileName = multipartFile.getOriginalFilename();
        if(!fileName.endsWith("xlsx")&&!fileName.endsWith("xls")){
            return "file is not xlsx,xls,try again choose ";
        }
        //MultipartFile转换成File
        File file= MultipartFile2FileUtil.MultipartFile2File(multipartFile);
        String msg ="";
        //需要解析的Excel文件
        try {
            //获取工作簿
            *//**
             * 构造函数获取一个FileInputStream对象
             * FileUtils.openInputStream 调用了 FileInputStream 的构造函数去打开一个文件（open0是一个本地方法，打开指定文件进行读取）
             * 对FileInputStream中的open调用open0方法---> https://blog.csdn.net/zhlily1/article/details/109468154
             *//*
            FileInputStream fs = FileUtils.openInputStream(file);
            XSSFWorkbook workbook = new XSSFWorkbook(fs);
            //获取最Excel中的sheet数量
            int numberOfSheets = workbook.getNumberOfSheets();
            for (int j=0;j<1;j++){
                //获取第一个工作表
                XSSFSheet hs = workbook.getSheetAt(j);
                //获取Sheet的第一个行号和最后一个行号
                int last = hs.getLastRowNum();
                int first = hs.getFirstRowNum();
                //遍历获取单元格里的信息
                List<KeyBasicDataVO> list = new ArrayList<>();
                XSSFRow fRow  = hs.getRow(0);
                if(fRow==null){
                    msg="data is error,title is missing";
                    continue;
                }
                XSSFCell fCell = fRow.getCell(0);
                if(fCell==null){
                    msg="data is error,title is missing";
                    continue;
                }
                //注：row为行   cell为列
                for (int i = first; i < last; i++) {
                    XSSFRow row  = hs.getRow(i+1);
                    XSSFCell cell = row.getCell(0);
                    if(cell==null){
                        msg = "first cell have empty data,please check agin";
                        break;
                    }
                    String cell1 = cell.getStringCellValue();
                    //可以在这里遍历row，获取当前行每列的数据
                    KeyBasicDataVO vo = new KeyBasicDataVO();
                    vo.setKind(kind);
                    vo.setName(cell1);
                    XSSFCell cellFirst = row.getCell(1);
                    if(cellFirst!=null){
                        String cellValue = cellFirst.getStringCellValue();
                        vo.setKeyCode(cellValue);
                    }
                    list.add(vo);
                }
                if(!CollectionUtils.isEmpty(list)){
                    msg = importBasic(list,false);
                }

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //清空文件缓存，并且调用delete0关闭文件
        MultipartFile2FileUtil.deleteFile(file);
        return msg;
    }*/

/*
    public String importBasic(List<KeyBasicDataVO> dataVoList, Boolean isUpdateSupport)
    {
        if (CollectionUtils.isEmpty(dataVoList) || dataVoList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //String password = configService.selectConfigByKey("sys.user.initPassword");
        for (KeyBasicDataVO vo : dataVoList)
        {
            try
            {
                if(!StringUtils.isEmpty(vo.getKeys())){
                    KeyBasicDataVO key = checkExistsBasicDataByKey(vo.getKeys());
                    if (key !=null){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum +"、 " + vo.getName() +":"+ vo.getKeys() +" 快捷键已存在");
                    }
                }
                // 验证是否存在这个用户
                KeyBasicDataVO basicDataDao = checkExistsBasicDataByName(vo.getName(),vo.getKind());
                if (basicDataDao == null)
                {
                    this.addBasicData(vo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、 " + vo.getName() +" 导入成功");
                }
                else if (isUpdateSupport)
                {
                    this.modifyBasicData(vo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、 " + vo.getName() +" 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum +"、 " + vo.getName() +" 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、 " + vo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
            //throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "success,恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }*/


    @Override
    public PageResult<KeyBasicDataVO> queryBasicInfo(PageInput<KeyBasicQueryVO> alarmPageQuery) {
        int total = basicDataDao.queryBasicCount(alarmPageQuery.getData());
        PageResult<KeyBasicDataVO> result = new PageResult<>(alarmPageQuery.getCurPage(), alarmPageQuery.getPageSize(), total);
        if (0 < total) {
            result.setData(basicDataDao.queryBasicByPage(result.getStartIndex(), alarmPageQuery.getPageSize(),
                    alarmPageQuery.getData()));
        }
        return result;
    }

}
